﻿#pragma once

#include "playfair/playfair.h"
#include "ppltasks.h"
#include <assert.h>
using namespace Platform;

namespace CCode
{
    public ref class Fairplay sealed
    {
    private:
        fairplay_t* fp = nullptr;
    public:
        
        Fairplay()
        {
            fp = fairplay_init();
        }

        int setup(const Array<uint8>^ input, Array<uint8>^* output)
        {
            assert(input->Length == 16);
            uint8* o = new uint8[142];         
            int r = fairplay_setup(fp, input->Data, o);
            if (r == 0)
            {
                *output = ref new Array<uint8>(o, 142);
            }
            delete[] o;
            return r;
        }

        int handshake(const Array<uint8>^ input, Array<uint8>^* output)
        {
            assert(input->Length == 164);
            uint8* o = new uint8[32];
            int r = fairplay_handshake(fp, input->Data, o);
            if (r == 0)
            {
                *output = ref new Array<uint8>(o, 32);
            }
            delete[] o;
            return r;
        }

        int decrypt(const Array<uint8>^ input, Array<uint8>^* output)
        {
            uint8* o = new uint8[16];
            int r = fairplay_decrypt(fp, input->Data, o);
            if (r == 0)
            {
                *output = ref new Array<uint8>(o, 16);
            }
            delete[] o;
            return r;
        }

        void destroy()
        {
            fairplay_destroy(fp);
            fp = nullptr;
        }
    };
}
